package com.nbicc.dp.wsgateway.holder;

import com.nbicc.dp.wsgateway.model.WsPanel;
import com.nbicc.dp.wsgateway.model.WsWidgetInstance;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: lilingyan
 */
@Slf4j
@Data
@Component
public class PanelHolder {

    private  Map<String , WsPanel> wsPanelMap = new ConcurrentHashMap<String, WsPanel>();

    /**
     * 加入看板
     * @param panelSerialNum
     * @param wsPanel
     */
    public void addWsPanel(String panelSerialNum , WsPanel wsPanel){
        wsPanelMap.put(panelSerialNum , wsPanel);
        log.info("看板上线"+wsPanel);
    }

    /**
     * 获取看板
     * @param panelSerialNum
     * @return
     */
    public WsPanel getWsPanel(String panelSerialNum){
        return  wsPanelMap.get(panelSerialNum);
    }

    /**
     * 查询包含某一个控件实例的看板
     * @param wsWidgetInstance
     * @return
     */
    public List<WsPanel> getWsPanelsThatContainsWsWidget(WsWidgetInstance wsWidgetInstance){
        List<WsPanel> wsPanelList = new ArrayList<>();
        for (WsPanel wsPanel : wsPanelMap.values()) {
           if( wsPanel.getWsWidgetInstanceSet().contains(wsWidgetInstance)){
               wsPanelList.add(wsPanel);
           }
        }
        return wsPanelList;
    }

    public List<WsPanel> getWsPanelsThatContainsWsWidget(Integer wsWidgetInstanceId){
        WsWidgetInstance wsWidgetInstance = new WsWidgetInstance();
        wsWidgetInstance.setWidgetInstanceId(wsWidgetInstanceId);
        return  getWsPanelsThatContainsWsWidget(wsWidgetInstance);
    }

    /**
     * 使用看板连接的sessionuI删除看板在线信息
     * @param session
     */
    public void removeByPanelSession(WebSocketSession session){
        Iterator<Map.Entry<String, WsPanel>> it = wsPanelMap.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, WsPanel> entry = it.next();
            WsPanel wsPanel = entry.getValue();
            log.info("看板下线："+wsPanel);
            if(wsPanel.getSession().getId().equals(session.getId())){
                it.remove();
                break;
            }
        }
    }


}
